from dkeep.settings import SECRET_KEY
import jwt
from datetime import timedelta
from datetime import datetime


class MJwt():
    def __init__(self):
        self.secret = SECRET_KEY
    def jwt_encode(self, userid, roleid, exp_time=None):
        # 如果未指定过期时间，则默认为1小时后过期
        if exp_time is None:
            exp_time = datetime.utcnow() + timedelta(hours=1)
        payload = {
            'userid': userid,
            'roleid': roleid,
            'exp': exp_time
        }
        return jwt.encode(payload, self.secret, algorithm="HS256")

    # 解密
    def jwt_decode(self, token):
        try:
            payload = jwt.decode(token, self.secret, algorithms=["HS256"])
            # 可以在这里添加额外的验证逻辑，例如检查userid或roleid的有效性
            return payload
        except jwt.ExpiredSignatureError:
            raise Exception("Token has expired")
        except jwt.InvalidTokenError:
            raise Exception("Invalid token")

myjwt=MJwt()
